<template>
  <div class="page-container">
    <!-- 操作栏 -->
    <div class="filter-container">
      <el-button type="success" @click="showCreateDialog">新增菜单</el-button>
    </div>

    <!-- 树形表格 -->
    <el-table
        :data="menuList"
        row-key="id"
        border
        default-expand-all
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
    >
      <el-table-column label="菜单名称" prop="name" width="200" />
      <el-table-column label="图标" prop="icon" width="120">
        <template #default="{ row }">
          <el-icon v-if="row.icon">
            <component :is="row.icon" />
          </el-icon>
        </template>
      </el-table-column>
      <el-table-column label="路由路径" prop="path" />
      <el-table-column label="排序" prop="sort" width="100" />
      <el-table-column label="状态" width="120">
        <template #default="{ row }">
          <el-tag :type="row.status ? 'success' : 'danger'">
            {{ row.status ? '启用' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="220" align="center">
        <template #default="{ row }">
          <el-button size="small" @click="handleEdit(row)">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDelete(row.id)"
          >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 新增/编辑对话框 -->
    <el-dialog
        v-model="dialogVisible"
        :title="dialogType === 'create' ? '新增菜单' : '编辑菜单'"
    >
      <el-form
          ref="menuForm"
          :model="currentMenu"
          :rules="rules"
          label-width="80px"
      >
        <el-form-item label="父菜单">
          <el-cascader
              v-model="currentMenu.parentId"
              :options="menuOptions"
              :props="{ checkStrictly: true, value: 'id', label: 'name' }"
              clearable
          />
        </el-form-item>
        <el-form-item label="菜单名称" prop="name">
          <el-input v-model="currentMenu.name" />
        </el-form-item>
        <el-form-item label="图标" prop="icon">
          <el-icon-picker v-model="currentMenu.icon" />
        </el-form-item>
        <el-form-item label="路由路径" prop="path">
          <el-input v-model="currentMenu.path" />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="currentMenu.sort" :min="0" />
        </el-form-item>
        <el-form-item label="状态">
          <el-switch v-model="currentMenu.status" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useMenuStore } from '@/store/menu'

const menuStore = useMenuStore()

// 数据状态
const menuList = ref([])
const menuOptions = ref([])
const loading = ref(false)

// 对话框相关
const dialogVisible = ref(false)
const dialogType = ref('create')
const currentMenu = reactive({
  id: null,
  parentId: null,
  name: '',
  icon: '',
  path: '',
  sort: 0,
  status: true
})

// 表单验证规则
const rules = reactive({
  name: [
    { required: true, message: '请输入菜单名称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  path: [{ required: true, message: '请输入路由路径', trigger: 'blur' }]
})

// 生命周期钩子
onMounted(() => {
  fetchData()
})

// 获取数据
const fetchData = async () => {
  loading.value = true
  try {
    await menuStore.fetchMenus()
    menuList.value = menuStore.list
    generateMenuOptions()
  } finally {
    loading.value = false
  }
}

// 生成级联选择器选项
const generateMenuOptions = () => {
  const options = []
  const addNode = (node) => {
    const item = {
      id: node.id,
      name: node.name,
      children: []
    }
    if (node.children && node.children.length) {
      node.children.forEach(child => addNode(child, item.children))
    }
    return item
  }
  menuList.value.forEach(node => options.push(addNode(node)))
  menuOptions.value = options
}

// 显示创建对话框
const showCreateDialog = () => {
  dialogType.value = 'create'
  dialogVisible.value = true
  Object.assign(currentMenu, {
    id: null,
    parentId: null,
    name: '',
    icon: '',
    path: '',
    sort: 0,
    status: true
  })
}

// 显示编辑对话框
const handleEdit = (row) => {
  dialogType.value = 'edit'
  dialogVisible.value = true
  Object.assign(currentMenu, { ...row })
}

// 提交表单
const submitForm = async () => {
  try {
    if (dialogType.value === 'create') {
      await menuStore.createMenu(currentMenu)
    } else {
      await menuStore.updateMenu(currentMenu.id, currentMenu)
    }
    dialogVisible.value = false
    fetchData()
  } catch (error) {
    console.error('操作失败:', error)
  }
}

// 删除处理
const handleDelete = async (id) => {
  try {
    await menuStore.deleteMenu(id)
    fetchData()
  } catch (error) {
    console.error('删除失败:', error)
  }
}
</script>

<style scoped>
.page-container {
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.filter-container {
  margin-bottom: 20px;
}
</style>